package com.wh.springbootshiromanyrealm.config;

import com.wh.springbootshiromanyrealm.modularauthenticate.CustomModularRealmAuthenticator;
import com.wh.springbootshiromanyrealm.realm.MyAdminRealm;
import com.wh.springbootshiromanyrealm.realm.MyUserRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Auther: HuiEr
 * @Date: 2020/3/4 21:20
 * @Description
 */
@SpringBootConfiguration
public class ShiroConfig {
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        Map<String, String> maps = new LinkedHashMap<>();

        maps.put("/toLogin","anon");
        maps.put("/adminLogin","anon");
        maps.put("/userLogin","anon");

        maps.put("/**","authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(maps);
        shiroFilterFactoryBean.setUnauthorizedUrl("/toLogin");
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager());
        return shiroFilterFactoryBean;
    }
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setAuthenticator(customModularRealmAuthenticator());

        ArrayList<Realm> realms = new ArrayList<>();
        realms.add(myAdminRealm());
        realms.add(myUserRealm());
        defaultWebSecurityManager.setRealms(realms);
        return defaultWebSecurityManager;
    }
    @Bean
    public MyAdminRealm myAdminRealm(){
        MyAdminRealm myAdminRealm = new MyAdminRealm();
        return myAdminRealm;
    }
    @Bean
    public MyUserRealm myUserRealm(){
        MyUserRealm myUserRealm = new MyUserRealm();
        return myUserRealm;
    }

    @Bean
    public CustomModularRealmAuthenticator customModularRealmAuthenticator(){
        CustomModularRealmAuthenticator customModularRealmAuthenticator = new CustomModularRealmAuthenticator();
        return customModularRealmAuthenticator;
    }
}
